package com.sskj.b70.v.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sskj.b70.R;
import com.sskj.b70.common.App;
import com.sskj.b70.p.activity.RegisterPresenter;
import com.sskj.b70.utils.CheckUtil;
import com.sskj.b70.utils.ClickUtil;
import com.sskj.b70.utils.DisposUtil;
import com.sskj.b70.utils.MD5Utils;
import com.sskj.b70.utils.ToastUtil;
import com.sskj.b70.v.base.BaseActivity;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

/**
 * <pre>
 *     author : wk_math
 *     e-mail : wk_math@163.com
 *     time   : 2018/04/02
 *     desc   :注册界面
 *     version: 1.0
 * </pre>
 */

public class RegisterActivity extends BaseActivity<RegisterPresenter> {
    @BindView(R.id.tv_goto_login)
    TextView tvGotoLogin;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.iv_delete)
    ImageView ivDelete;
    @BindView(R.id.bt_next_step)
    Button btNextStep;
    @BindView(R.id.register_protocol)
    TextView registerProtocol;  // 注册协议
    @BindView(R.id.et_verification_code)
    EditText etVerificationCode;  // 验证码输入框
    @BindView(R.id.register_code)
    TextView registerCode;  // 验证码
    @BindView(R.id.register_pwd)
    EditText registerPwd;  // 输入密码
    @BindView(R.id.register_pwd_two)
    EditText registerPwdTwo;  // 再次输入密码
    @BindView(R.id.register_invitation_code)
    EditText registerInvitationCode;  // 邀请码
    private DisposableSubscriber<Long> disposableSubscriber;
    @BindView(R.id.checkbox)
    CheckBox checkbox;   // 单选框  同意用户协议

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_register;
    }

    @Override
    public RegisterPresenter getPresenter() {
        return new RegisterPresenter();
    }

    @Override
    protected void onViewBinding() {
        ClickUtil.click(registerCode, () -> {   // 获取短信验证码
            if (CheckUtil.isEmail(etPhone.getText().toString())) {
                registerCode.setEnabled(false);
                mPresenter.sendEmailCode(etPhone.getText().toString());
            } else if (CheckUtil.isMobile(etPhone.getText().toString())) {
                registerCode.setEnabled(false);
                mPresenter.sendCode(etPhone.getText().toString());
            } else {
                ToastUtil.showShort(getString(R.string.register_input_right_mobile));
                etPhone.setText("");
            }
        });

        ClickUtil.click(ivDelete, () -> etPhone.setText(""));
        ClickUtil.click(btNextStep, () -> {
            String phoneNumber = etPhone.getText().toString().trim();
            String code = etVerificationCode.getText().toString().trim();
            String registerPwdCon = registerPwd.getText().toString().trim();
            String registerPwdTwoCon = registerPwdTwo.getText().toString().trim();
            String registerInvitationCodeCon = registerInvitationCode.getText().toString().trim();
            if (!CheckUtil.isMobile(phoneNumber) && !CheckUtil.isEmail(phoneNumber)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strRegisterActivity2));
                etPhone.setText("");
                return;
            }
            if (TextUtils.isEmpty(code)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strRegisterActivity4));
                return;
            }
            if (!CheckUtil.isPayPwd(registerPwdCon) || !CheckUtil.isPayPwd(registerPwdTwoCon)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strRegisterActivity5));
                return;
            }
            if (!registerPwdCon.equals(registerPwdTwoCon)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strRegisterActivity6));
                return;
            }
//            if (TextUtils.isEmpty(registerInvitationCodeCon)) {
//                ToastUtil.showShort(App.INSTANCE.getString(R.string.strRegisterActivity7));
//                return;
//            }
            if (!checkbox.isChecked()) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.strRegisterActivity8));
                return;
            }
            mPresenter.register(phoneNumber, MD5Utils.getMd5Value(registerPwdTwoCon), code, TextUtils.isEmpty(registerInvitationCodeCon)?null:registerInvitationCodeCon);
        });
        ClickUtil.click(tvGotoLogin, () -> {
                    startActivity(new Intent(this, LoginActivity.class));
                }
        );

        ClickUtil.click(registerProtocol, () -> startActivity(new Intent(this, WebActivity.class)));
    }

    public void sendCodeOk() {
        startCount();
    }

    public void sendCodeError() {
        registerCode.setEnabled(true);

    }

    /**
     * 获取验证码倒计时
     */
    public void startCount() {
        DisposUtil.close(disposableSubscriber);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                registerCode.setText(String.format(App.INSTANCE.getString(R.string.strRegisterActivity9), time));
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                registerCode.setText(App.INSTANCE.getString(R.string.strRegisterActivity10));
                registerCode.setEnabled(true);
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }

            }
        };
        etVerificationCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 6) {
                    btNextStep.setEnabled(true);
                } else {
                    btNextStep.setEnabled(false);
                }
            }
        });

        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    public void registerSuccess() {
        ToastUtil.showShort(App.INSTANCE.getString(R.string.strRegisterActivity11));
        startActivity(new Intent(this, LoginActivity.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DisposUtil.close(disposableSubscriber);
    }
}
